package com.example.a053testthreaddemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Timer;
import java.util.TimerTask;

public class basicThread extends AppCompatActivity {
    Button btnBasicThread;
    public TextView txtModify;
    public final static int UPDATE_NOW = 1;
    public mHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_thread);
        btnBasicThread = (Button) findViewById(R.id.btnBasic);
        txtModify = (TextView) findViewById(R.id.txtModify);
        handler = new mHandler();
        btnBasicThread.setOnClickListener(new mClick());
    }

    // 利用Handler类处理更新UI操作
    private class mHandler extends Handler {
        public void handleMessage(Message msg) {
            if (msg.what == UPDATE_NOW) {
                txtModify.setText("成功修改，不崩溃了！\n 自嘲2秒ing，返回主页！！");
                // 利用定时器，停顿2秒，返回主页面
                final Intent intent = new Intent(basicThread.this, MainActivity.class);
                Timer timer = new Timer();
                TimerTask tast = new TimerTask() {
                    @Override
                    public void run() {
                        startActivity(intent);
                    }
                };
                timer.schedule(tast, 2000); // 单位毫秒
            }
        }
    }

    // 继承方式，自定义线程类MyThread传递消息，让handler处理UI更新。
    class MyThread extends Thread {
        @Override
        public void run() { // 不能在线程里直接修改UI
            Message message = new Message();
            message.what = UPDATE_NOW;
            handler.sendMessage(message);
        }
    }

    // 监听事件
    class mClick implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            new MyThread().start(); // 启动线程基本方式
            /*
            // 下面的方式是Runnable接口的方式
            new Thread(new Runnable() {
                @Override
                public void run() { // 不能在线程里直接修改UI
                    Message message = new Message();
                    message.what = UPDATE_NOW;
                    handler.sendMessage(message);
                }
            }).start(); // Runnable
            */
        }
    }
}